import { useState } from 'react';
import { Eye, EyeOff, Mail, Lock, User, UserPlus } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import TitleBar from '@/components/common/TitleBar';
import { clsx } from 'clsx';

interface FormData {
  email: string;
  username: string;
  password: string;
  confirmPassword: string;
  acceptTerms: boolean;
}

const Register: React.FC = () => {
  const { register, isLoading, error } = useAuth();

  const [formData, setFormData] = useState<FormData>({
    email: '',
    username: '',
    password: '',
    confirmPassword: '',
    acceptTerms: false,
  });

  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [formErrors, setFormErrors] = useState<Partial<FormData>>({});

  const validateForm = (): boolean => {
    const errors: Partial<FormData> = {};

    if (!formData.email) {
      errors.email = '请输入邮箱地址';
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      errors.email = '请输入有效的邮箱地址';
    }

    if (!formData.username) {
      errors.username = '请输入用户名';
    } else if (formData.username.length < 3) {
      errors.username = '用户名至少需要3个字符';
    } else if (!/^[a-zA-Z0-9_]+$/.test(formData.username)) {
      errors.username = '用户名只能包含字母、数字和下划线';
    }

    if (!formData.password) {
      errors.password = '请输入密码';
    } else if (formData.password.length < 8) {
      errors.password = '密码至少需要8个字符';
    } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(formData.password)) {
      errors.password = '密码必须包含大小写字母和数字';
    }

    if (!formData.confirmPassword) {
      errors.confirmPassword = '请确认密码';
    } else if (formData.password !== formData.confirmPassword) {
      errors.confirmPassword = '两次输入的密码不一致';
    }

    if (!formData.acceptTerms) {
      errors.acceptTerms = true;
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) return;

    await register({
      email: formData.email,
      username: formData.username,
      password: formData.password,
      confirmPassword: formData.confirmPassword,
      acceptTerms: formData.acceptTerms,
    });
  };

  const handleInputChange = (field: keyof FormData, value: string | boolean) => {
    setFormData(prev => ({ ...prev, [field]: value }));

    // Clear field error when user starts typing
    if (formErrors[field]) {
      setFormErrors(prev => ({ ...prev, [field]: undefined }));
    }
  };

  const getPasswordStrength = (password: string): string => {
    let score = 0;
    if (password.length >= 8) score++;
    if (/[a-z]/.test(password)) score++;
    if (/[A-Z]/.test(password)) score++;
    if (/\d/.test(password)) score++;
    if (/[^a-zA-Z\d]/.test(password)) score++;

    if (score < 2) return 'weak';
    if (score < 4) return 'medium';
    return 'strong';
  };

  const passwordStrength = getPasswordStrength(formData.password);
  const strengthColors: Record<string, string> = {
    weak: 'bg-red-500',
    medium: 'bg-yellow-500',
    strong: 'bg-green-500',
  };

  const strengthLabels: Record<string, string> = {
    weak: '弱',
    medium: '中',
    strong: '强',
  };

  return (
    <div className='h-screen w-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex flex-col overflow-hidden'>
      {/* Custom Title Bar */}
      <TitleBar title='Movie Tools' />

      <div className='flex-1 flex items-center justify-center px-8'>
        <div className='w-full max-w-md'>
          <div className='bg-white/10 backdrop-blur-xl rounded-3xl shadow-2xl border border-white/20 p-8'>
            <div className='text-center mb-8'>
              <div className='w-16 h-16 bg-gradient-to-br from-purple-500 to-pink-500 rounded-2xl flex items-center justify-center mx-auto mb-6'>
                <UserPlus className='w-8 h-8 text-white' />
              </div>
              <h1 className='text-3xl font-bold text-white mb-2'>Create Account</h1>
              <p className='text-white/70'>Join us and start your journey</p>
            </div>

            {error && (
              <div className='p-4 mb-6 bg-red-500/20 backdrop-blur-sm rounded-xl border border-red-500/30'>
                <p className='text-sm text-red-200'>{error}</p>
              </div>
            )}

            <form onSubmit={handleSubmit} className='space-y-6'>
              {/* Email Field */}
              <div>
                <label htmlFor='email' className='block mb-3 text-sm font-medium text-white/90'>
                  Email Address
                </label>
                <div className='relative'>
                  <div className='flex absolute inset-y-0 left-0 items-center pl-4 pointer-events-none'>
                    <Mail className='w-5 h-5 text-white/60' />
                  </div>
                  <input
                    id='email'
                    name='email'
                    type='email'
                    autoComplete='email'
                    required
                    value={formData.email}
                    onChange={e => handleInputChange('email', e.target.value)}
                    className={clsx(
                      'w-full px-4 py-4 pl-12 bg-white/10 backdrop-blur-sm border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all duration-300',
                      formErrors.email && 'border-red-400 focus:ring-red-500'
                    )}
                    placeholder='Enter your email'
                  />
                </div>
                {formErrors.email && (
                  <p className='mt-2 text-sm text-red-300'>{formErrors.email}</p>
                )}
              </div>

              {/* Username Field */}
              <div>
                <label htmlFor='username' className='block mb-3 text-sm font-medium text-white/90'>
                  Full Name
                </label>
                <div className='relative'>
                  <div className='flex absolute inset-y-0 left-0 items-center pl-4 pointer-events-none'>
                    <User className='w-5 h-5 text-white/60' />
                  </div>
                  <input
                    id='username'
                    name='username'
                    type='text'
                    autoComplete='username'
                    required
                    value={formData.username}
                    onChange={e => handleInputChange('username', e.target.value)}
                    className={clsx(
                      'w-full px-4 py-4 pl-12 bg-white/10 backdrop-blur-sm border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all duration-300',
                      formErrors.username && 'border-red-400 focus:ring-red-500'
                    )}
                    placeholder='Enter your full name'
                  />
                </div>
                {formErrors.username && (
                  <p className='mt-2 text-sm text-red-300'>{formErrors.username}</p>
                )}
              </div>

              {/* Password Field */}
              <div>
                <label htmlFor='password' className='block mb-3 text-sm font-medium text-white/90'>
                  Password
                </label>
                <div className='relative'>
                  <div className='flex absolute inset-y-0 left-0 items-center pl-4 pointer-events-none'>
                    <Lock className='w-5 h-5 text-white/60' />
                  </div>
                  <input
                    id='password'
                    name='password'
                    type={showPassword ? 'text' : 'password'}
                    autoComplete='new-password'
                    required
                    value={formData.password}
                    onChange={e => handleInputChange('password', e.target.value)}
                    className={clsx(
                      'w-full px-4 py-4 pl-12 pr-12 bg-white/10 backdrop-blur-sm border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all duration-300',
                      formErrors.password && 'border-red-400 focus:ring-red-500'
                    )}
                    placeholder='Create a strong password'
                  />
                  <button
                    type='button'
                    className='flex absolute inset-y-0 right-0 items-center pr-4 text-white/60 hover:text-white transition-colors'
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? <EyeOff className='w-5 h-5' /> : <Eye className='w-5 h-5' />}
                  </button>
                </div>

                {/* Password Strength Indicator */}
                {formData.password && (
                  <div className='mt-3'>
                    <div className='flex items-center space-x-3'>
                      <div className='flex-1 h-2 bg-white/20 rounded-full overflow-hidden'>
                        <div
                          className={`h-full transition-all duration-300 ${strengthColors[passwordStrength]}`}
                          style={{
                            width:
                              passwordStrength === 'weak'
                                ? '33%'
                                : passwordStrength === 'medium'
                                  ? '66%'
                                  : '100%',
                          }}
                        />
                      </div>
                      <span className='text-xs text-white/70 font-medium'>
                        {strengthLabels[passwordStrength]}
                      </span>
                    </div>
                  </div>
                )}

                {formErrors.password && (
                  <p className='mt-2 text-sm text-red-300'>{formErrors.password}</p>
                )}
              </div>

              {/* Confirm Password Field */}
              <div>
                <label
                  htmlFor='confirmPassword'
                  className='block mb-3 text-sm font-medium text-white/90'
                >
                  Confirm Password
                </label>
                <div className='relative'>
                  <div className='flex absolute inset-y-0 left-0 items-center pl-4 pointer-events-none'>
                    <Lock className='w-5 h-5 text-white/60' />
                  </div>
                  <input
                    id='confirmPassword'
                    name='confirmPassword'
                    type={showConfirmPassword ? 'text' : 'password'}
                    autoComplete='new-password'
                    required
                    value={formData.confirmPassword}
                    onChange={e => handleInputChange('confirmPassword', e.target.value)}
                    className={clsx(
                      'w-full px-4 py-4 pl-12 pr-12 bg-white/10 backdrop-blur-sm border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all duration-300',
                      formErrors.confirmPassword && 'border-red-400 focus:ring-red-500'
                    )}
                    placeholder='Confirm your password'
                  />
                  <button
                    type='button'
                    className='flex absolute inset-y-0 right-0 items-center pr-4 text-white/60 hover:text-white transition-colors'
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  >
                    {showConfirmPassword ? (
                      <EyeOff className='w-5 h-5' />
                    ) : (
                      <Eye className='w-5 h-5' />
                    )}
                  </button>
                </div>
                {formErrors.confirmPassword && (
                  <p className='mt-2 text-sm text-red-300'>{formErrors.confirmPassword}</p>
                )}
              </div>

              {/* Terms & Conditions */}
              <div>
                <div className='flex items-start'>
                  <input
                    id='acceptTerms'
                    name='acceptTerms'
                    type='checkbox'
                    checked={formData.acceptTerms}
                    onChange={e => handleInputChange('acceptTerms', e.target.checked)}
                    className={clsx(
                      'mt-1 h-4 w-4 rounded border-white/30 bg-white/10 text-purple-500 focus:ring-purple-500 focus:ring-offset-0',
                      formErrors.acceptTerms && 'border-red-400'
                    )}
                  />
                  <label htmlFor='acceptTerms' className='block ml-3 text-sm text-white/80'>
                    I agree to the{' '}
                    <a
                      href='#'
                      className='font-medium text-purple-300 hover:text-purple-200 transition-colors'
                    >
                      Terms of Service
                    </a>{' '}
                    and{' '}
                    <a
                      href='#'
                      className='font-medium text-purple-300 hover:text-purple-200 transition-colors'
                    >
                      Privacy Policy
                    </a>
                  </label>
                </div>
                {formErrors.acceptTerms && (
                  <p className='mt-2 text-sm text-red-300'>{formErrors.acceptTerms}</p>
                )}
              </div>

              {/* Submit Button */}
              <button
                type='submit'
                disabled={isLoading}
                className='w-full bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-semibold py-4 px-6 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-[1.02] disabled:opacity-50 disabled:cursor-not-allowed'
              >
                {isLoading ? (
                  <div className='flex items-center justify-center'>
                    <div className='w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin mr-2'></div>
                    Creating account...
                  </div>
                ) : (
                  'Create Account'
                )}
              </button>
            </form>

            {/* Login Link */}
            <div className='mt-8 text-center'>
              <p className='text-sm text-white/70'>
                Already have an account?{' '}
                <a
                  href='/auth/login'
                  className='text-purple-300 hover:text-purple-200 font-medium transition-colors'
                >
                  Sign In
                </a>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
export default Register;
